//
//  UIImage+common.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/21.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "UIImage+common.h"

@implementation UIImage (common)

- (NSData *)imageCompression:(UIImageCompression)compression {
    NSData *imageData = UIImageJPEGRepresentation(self, 1.0);
    switch (compression) {
        case 0:{
            return imageData;
        }
            break;
            
        default:{
            long maxLength = compression == 1 ? (KscreenWidth * KscreenHeight) : 720 * 1024;
            CGFloat max    = 1;
            CGFloat min    = 0;
            for (int i = 0; i < 6; ++i) {
                compression = (max + min) / 2;
                imageData   = UIImageJPEGRepresentation(self, compression);
                if (imageData.length < maxLength * 0.9) {
                    min = compression;
                } else if (imageData.length > maxLength) {
                    max = compression;
                } else {
                    break;
                }
            }
            return imageData;
        }
            break;
    }
}

- (UIImage *)drawImageWithSize:(CGSize)size {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    
    UIGraphicsBeginImageContext(rect.size);
    
    [self drawInRect:rect];  // scales image to rect
    
    UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resImage;
}


@end
